package com.example.project.service.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.project.entity.Issue;
import com.example.project.entity.IssuePrioritie;
import com.example.project.entity.IssueStatus;
import com.example.project.entity.Project;
import com.example.project.mapper.IssueMapper;
import com.example.project.mapper.ProjectMapper;
import com.example.project.mapper.StatisticsMapper;
import com.example.project.service.CommonService;
import com.example.project.service.IssueStatusService;
import com.example.project.service.StatisticsService;

/**
 * 统计管理Service实现
 * 
 * @author ruoyi
 * @date 2025-10-23
 */
@Service
public class StatisticsServiceImpl implements StatisticsService {

	@Autowired
	private ProjectMapper projectMapper;

	@Autowired
	private IssueMapper issueMapper;

	@Autowired
	private StatisticsMapper statisticsMapper;

	@Autowired
	private CommonService commonService;

	@Autowired
	private IssueStatusService issueStatusService;

	@Override
	public List<Map<String, Object>> getProjectStatistics() {
		List<Map<String, Object>> result = new ArrayList<>();

		// 获取项目总数
		Long totalProjects = projectMapper.getCount();

		Map<String, Object> totalProjectsMap = new HashMap<>();
		totalProjectsMap.put("name", "总项目数");
		totalProjectsMap.put("count", totalProjects);
		result.add(totalProjectsMap);

		// 获取不同状态的项目数量
		Map<String, Object> activeProjects = new HashMap<>();
		activeProjects.put("name", "进行中项目");
		activeProjects.put("count", projectMapper.selectCountByState(1)); // 假设状态1为活跃
		result.add(activeProjects);

		return result;
	}

	@Override
	public List<Map<String, Object>> getIssueStatistics() {
		List<Map<String, Object>> result = new ArrayList<>();

		// 获取问题总数
		long totalIssues = issueMapper.getCount(null);

		Map<String, Object> totalIssuesMap = new HashMap<>();
		totalIssuesMap.put("name", "总问题数");
		totalIssuesMap.put("count", totalIssues);
		result.add(totalIssuesMap);

		// 获取待处理问题数量
		Map<String, Object> pendingIssues = new HashMap<>();
		pendingIssues.put("name", "待处理问题");
		pendingIssues.put("count", issueMapper.selectCountByStatus(1L)); // 假设状态1为待处理
		result.add(pendingIssues);

		return result;
	}

	@Override
	public Map<String, Object> getProjectChartData() {
		Map<String, Object> chartData = new HashMap<>();

		// 项目状态分布
		List<String> labels = new ArrayList<>();
		List<Integer> data = new ArrayList<>();

		labels.add("活跃项目");
		data.add(projectMapper.selectCountByState(1));

		labels.add("已完成");
		data.add(projectMapper.selectCountByState(2));

		labels.add("暂停中");
		data.add(projectMapper.selectCountByState(3));

		chartData.put("labels", labels);
		chartData.put("data", data);

		return chartData;
	}

	@Override
	public Map<String, Object> getIssueChartData() {
		Map<String, Object> chartData = new HashMap<>();

		List<IssueStatus> issueStatusList = commonService.getIssueStatusList();

		List<Map<String, Object>> statusTotalList = issueMapper.selectIssueStatusTotal();

		Map<String, Integer> statusMap = statusTotalList.stream().collect(Collectors.toMap(
				k -> String.valueOf(k.get("status_id")), v -> Integer.parseInt(String.valueOf(v.get("issue_count")))));
		// 问题状态分布
		List<String> labels = new ArrayList<>();
		List<Integer> data = new ArrayList<>();
		issueStatusList.forEach(status -> {
			labels.add(status.getName());
			Integer total = statusMap.get(String.valueOf(status.getId()));
			data.add(total != null ? total : 0);
		});

		chartData.put("labels", labels);
		chartData.put("data", data);

		return chartData;
	}

	@Override
	public List<Map<String, Object>> getProjectIssueDistribution() {
		try {
			List<Map<String, Object>> result = issueMapper.selectProjectIssueDistribution();
			return result != null ? result : new ArrayList<>();
		} catch (Exception e) {
			return new ArrayList<>();
		}
	}

	@Override
	public List<Map<String, Object>> getIssueStatusStats() {
		try {
			List<Map<String, Object>> result = issueMapper.selectIssueStatusTotal();
			if (result != null) {
				List<IssueStatus> statusList = commonService.getIssueStatusList();
				Map<Long, String> statusMap = statusList.stream()
						.collect(Collectors.toMap(IssueStatus::getId, IssueStatus::getName));

				// 转换状态ID为状态名称
				for (Map<String, Object> item : result) {
					Long statusId = Long.parseLong(String.valueOf(item.get("status_id")));
					String statusName = statusMap.getOrDefault(statusId, "状态" + statusId);
					item.put("status_name", statusName);
				}
			}
			return result != null ? result : new ArrayList<>();
		} catch (Exception e) {
			return new ArrayList<>();
		}
	}

	@Override
	public List<Map<String, Object>> getIssuePriorityStats() {
		try {
			List<Map<String, Object>> result = issueMapper.selectIssuePriorityStats();
			if (result != null) {
				Map<Long, IssuePrioritie> priorityMap = commonService.getIssuePrioritieMap();
				// 转换优先级ID为优先级名称
				for (Map<String, Object> item : result) {
					Long priorityId = Long.parseLong(String.valueOf(item.get("priority_id")));
					IssuePrioritie issuePrioritie = priorityMap.get(priorityId);
					String priorityName = issuePrioritie != null ? issuePrioritie.getName() : "优先级" + priorityId;
					item.put("priority_name", priorityName);
				}
			}
			return result != null ? result : new ArrayList<>();
		} catch (Exception e) {
			return new ArrayList<>();
		}
	}

	@Override
	public List<Map<String, Object>> queryProjectForIssueDetail(String startDate, String endDate, int size) {
		// TODO Auto-generated method stub
		List<Map<String, Object>> issueTotalList = issueMapper.selectTotalGroupByProjectIdAndStatusId(startDate,
				endDate);
		Map<String, Integer> issueStatusTotalMap = issueTotalList.stream()
				.collect(Collectors.toMap(map -> map.get("project_id") + "_" + map.get("status_id"),
						map -> Integer.parseInt(String.valueOf(map.get("total")))));

		Map<Long, Long> issueTotalMap = issueTotalList.stream()
				.collect(Collectors.toMap(map -> Long.parseLong(map.get("project_id").toString()),
						map -> Long.parseLong(map.get("total").toString()),
						(existingValue, newValue) -> existingValue + newValue));

		List<IssueStatus> issueStatusList = commonService.getIssueStatusList();
		List<Project> projectList = commonService.getProjectList();
		projectList = new ArrayList<>(projectList.stream().filter(info -> info.getState() == 1).toList());
		projectList.sort(Comparator.comparing(Project::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))
				.thenComparing(Project::getId));
		if (size != 0) {
			projectList = projectList.stream().limit(size).collect(Collectors.toList());
		}

		List<Map<String, Object>> list = Lists.newArrayList();
		projectList.stream().forEach(info -> {
			Map<String, Object> map = new HashMap<String, Object>();
			Long projectId = info.getId();

			map.put("projectName", info.getName());
			map.put("customerName", info.getCustomerName());
			map.put("state", info.getState() == 1 ? "运营中" : "已停运");

			Long issueTotal = issueTotalMap.get(projectId);
			map.put("issueTotal", issueTotal != null ? issueTotal : 0);
			for (IssueStatus issueStatus : issueStatusList) {
				Long issueStatusId = issueStatus.getId();
				Integer total = issueStatusTotalMap.get(projectId + "_" + issueStatusId);

				map.put("issueStatusName", issueStatus.getName());
				map.put("issueStatusId", issueStatusId);
				map.put("statusTotal" + issueStatusId, total != null ? total : 0);
			}
			list.add(map);
		});
//		List<Map<String, Object>> list = statisticsMapper.queryProjectForIssueDetail(endDate, endDate);
		return list;
	}

}